/**
 * 生成水印base64
 */
const watermarkImg = ({ fontSize = 16, text = "请勿外传", gap = 1, color = "rgba(0,0,0,0.3)" }) => {
	const canvas = document.createElement("canvas");
	const devicePixelRatio = window.devicePixelRatio || 1;
	fontSize *= devicePixelRatio;
	const font = `${fontSize}px serif`;
	const res = canvas.getContext("2d");
	if (!res || !(res instanceof CanvasRenderingContext2D)) {
		throw new Error("Failed to get 2D context");
	}
	const ctx: CanvasRenderingContext2D = res;
	// 获取文字宽度
	const { width } = ctx.measureText(text);
	const canvasSize = Math.max(100, width) + gap * devicePixelRatio;
	canvas.width = canvasSize;
	canvas.height = canvasSize;
	console.log(canvasSize, canvasSize);
	ctx.translate(canvas.width / 2, canvas.height / 2);
	ctx.rotate((Math.PI / 180) * -45);
	ctx.fillStyle = color;
	ctx.font = font;
	ctx.textAlign = "center";
	ctx.textBaseline = "middle";
	ctx.fillText(text, 0, 0);
	return {
		base64: canvas.toDataURL(),
		size: canvasSize,
		styleSize: canvasSize / devicePixelRatio,
	};
};

/**
 *  watermark 样式
 */
let style = `
display: block;
overflow: hidden;
position: absolute;
left: 0;
top: 0;
z-index: 9999;
width: 100%;
height: 100%;
background-repeat: repeat;
pointer-events: none;`;

const setWaterMark = (el: HTMLElement, binding: any) => {
	const { parentElement } = el;
	// 获取对应canvas相关base64 url
	const { base64 } = watermarkImg({ ...binding.value });
	const waterMark = document.createElement("div");
	waterMark.className = "water-mark";
	style = `${style}background-image: url(${base64})`;
	waterMark.setAttribute("style", style);
	if (parentElement) {
		// 将对应图片的父容器作为定位元素
		parentElement.setAttribute("style", "position: relative;");
		// 将图片元素移动到 waterMark 中
		parentElement.appendChild(waterMark);
	}
};
// 监听 DOM 变化
const createObserver = (el: HTMLElement) => {
	let waterMarkEl: any = null;
	if (el.parentElement) {
		waterMarkEl = el.parentElement.querySelector(".water-mark");
	}

	const observer = new MutationObserver((mutationsList) => {
		if (mutationsList.length) {
			const { removedNodes, type, target } = mutationsList[0];
			const currStyle = waterMarkEl.getAttribute("style");
			// DOM被删除了
			if (removedNodes[0] === waterMarkEl) {
				console.log("删除水印");
				const { parentElement } = el;
				if (!parentElement || !(parentElement instanceof HTMLElement)) {
					throw new Error("HTMLElement");
				}
				parentElement.setAttribute("style", "position: relative;");
				parentElement.appendChild(removedNodes[0]);
			} else if (type === "attributes" && target === waterMarkEl && currStyle !== style) {
				waterMarkEl.setAttribute("style", style);
			}
		}
	});
	if (el.parentElement) {
		observer.observe(el.parentElement, {
			childList: true,
			attributes: true,
			subtree: true,
		});
	}
};
// 初始化
const init = (el: HTMLElement, binding: any = {}) => {
	// 设置水印
	setWaterMark(el, binding);
	// 启动监控
	createObserver(el);
};

// 定义指令配置项
export default {
	mounted(el: HTMLElement, binding: any) {
		init(el, binding);
	},
};
